import decoder from "../other/321-92011"
import Logger from "../utils/Logger"
import * as THREE from "three"
import Chunk from "../other/321-8511"
import p from "../other/321-19131"
import Pbf from "pbf"
const f = new Logger("dam-loader")
export default class DamLoader {
  decoder: any
  constructor() {
    this.decoder = decoder
  }
  async load(e, t, s) {
    f.time("download")
    const r = await t.getFile(e, {
      responseType: "arraybuffer",
      onProgress: s
    })
    return f.timeEnd("download"), this.parse(r)
  }
  parse(e) {
    f.time("parse proto")
    const t = this.decoder.read(new Pbf(e))
    f.timeEnd("parse proto"), f.time("convert to webgl")
    const s = this.convertProtobufToSceneObject(t)
    return f.timeEnd("convert to webgl"), s
  }
  convertProtobufToSceneObject(e) {
    if (0 === e.chunk.length) return f.warn("No chunks in damfile..."), []
    const t = new THREE.Matrix4()
    t.set(1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1)
    return e.chunk.map(e => {
      const s = new THREE.BufferGeometry()
      s.setAttribute("position", new THREE.BufferAttribute(new Float32Array(e.vertices.xyz, 0, 3), 3)),
        e.vertices.uv.length > 0 && s.setAttribute("uv", new THREE.BufferAttribute(new Float32Array(e.vertices.uv, 0, 2), 2))
      s.setIndex(new THREE.BufferAttribute(new Uint32Array(e.faces.faces, 0, 1), 1))
      s.applyMatrix4(t)
      s.computeBoundingBox()
      const { group, subgroup } = p.xc(e.chunk_name)
      return new Chunk(group, subgroup, s, e.material_name)
    })
  }
}
